package com.ihrm.system.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.Constants;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.exception.CommonException;
import com.ihrm.domain.system.Role;
import com.ihrm.domain.system.RolePermission;
import com.ihrm.system.dao.RoleDao;
import com.ihrm.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    //添加角色
    @PostMapping("/role")
    public Result addRole(@RequestBody Role role) {
        role.setCompanyId(parseCompanyId());
        Integer num = roleService.insert(role);
        if (num > 0) {
            return Result.SUCCESS();
        } else {
            throw new CommonException(Constants.FAIL_CODE, "添加失败");
        }
    }

    //删除角色
    @DeleteMapping("/role/{id}")
    public Result delRole(@PathVariable String id) {
        Integer num = roleService.delRoleById(id);
        if (num > 0) {
            return Result.SUCCESS();
        } else {
            throw new CommonException(Constants.FAIL_CODE, "删除失败");
        }
    }

    //修改角色
    @PutMapping("/role/{id}")
    public Result updateRole(@PathVariable String id, @RequestBody Role role) {
        Integer num = roleService.updateRole(role);
        if (num > 0) {
            return Result.SUCCESS();
        } else {
            throw new CommonException(Constants.FAIL_CODE, "修改失败");
        }
    }

    //根据id查询角色
    @GetMapping("/role/{id}")
    public Result getRoleById(@PathVariable String id) {
        Role role = roleService.getRoleById(id);
        if (role != null) {
            return Result.SUCCESS(role);
        } else {
            throw new CommonException(Constants.FAIL_CODE, "角色不存在");
        }
    }


    //分页查询角色
    @GetMapping("/role")
    public Result pageFind(Integer page, Integer pagesize, Role role) {
        role.setCompanyId(parseCompanyId());
        PageResult pageResult = roleService.pageFind(page, pagesize, role);
        return Result.SUCCESS(pageResult);
    }

    //查询所有角色
    @GetMapping("/role/list")
    public Result findAll(Role role) {
        role.setCompanyId(parseCompanyId());
        List<Role> list = roleService.findAll(role);
        return Result.SUCCESS(list);
    }

    /**
     * 分配权限
     */
    @PutMapping("/role/assignPrem")
    public Result assignPrem(@RequestBody Map<String, Object> map) {
        roleService.assignPerms(map);
        return Result.SUCCESS();
    }

}
